﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Core.Contracts.QandA;
using TomNet.IMSC.Model.DbModels.QandA;
using TomNet.IMSC.Model.ViewModels;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Controllers.QandA
{
    [Description("动态管理")]
    public class DynamicController : BaseController
    {
        public IDynamicModelContract DynamicModelContract { get; set; }
        public IDynamicPropertiesModelContract DynamicPropertiesModelContract { get; set; }
        public IDynamicCheapRoomModelContract DynamicCheapRoomModelContract { get; set; }
        public IDynamicDecorationModelContract DynamicDecorationModelContract { get; set; }
        public IAreaContract AreaContract { get; set; }
        public IAgentCityContract AgentCityContract { get; set; }
        public IBuildingsContract BuildingsContract { get; set; } 
        public ILowPriceHousesContract LowPriceHousesContract { get; set; }
        public ILowPriceHouseBuildingsContract LowPriceHouseBuildingsContract { get; set; }
        public IDecorationCompanyContract DecorationCompanyContract { get; set; }
        #region 动态列表
        [Description("动态管理-列表")]
        public ActionResult DynamicIndex()
        {
            return View();
        }
        [HttpPost]
        public ActionResult DynamicIndexAsync(int pageIndex, int pageSize, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var Agentid = model.AgentId;
            var Agentcity = AgentCityContract.TrackEntities.Where(a => a.AgentID == 1);
            var Dynamic = DynamicModelContract.TrackEntities.Where(d => !d.IsDeleted);
            var data = from dc in Dynamic
                       select new
                       {
                           Id = dc.Id,

                           CityID = (from city in AreaContract.TrackEntities where city.Id == dc.CityID.ToString() select city.Name).FirstOrDefault(),
                           Title = dc.Title,
                           Subject = dc.Subject,
                           ReleaseTime = dc.ReleaseTime,
                           ShowIndex = dc.ShowIndex,
                       }; 

            if (!string.IsNullOrWhiteSpace(search))
            {
                data = data.Where(m => m.Title.Contains(search));
            }

            //数据总数
            var total = data.Count();

            //默认给一个排序的字段
            data = data.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            data = total > 0 ? data.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : data;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = data.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion 
        #region 动态添加
        [Description("动态管理-添加")]
        public ActionResult DynamicInsert()
        {
            //innerce();
            return View();
        }
        [HttpPost]
        public ActionResult DynamicInsertAsyunc(DynamicModel entity)
        {
            entity.ReleaseTime = DateTime.Now;

            var result = new AjaxResult(); 

            //开始事务
            DynamicPropertiesModelContract.Repository.UnitOfWork.BeginTransaction();

            try
            {  
                var query = DynamicModelContract.CheckExists(m => m.Title.Equals(entity.Title) && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的动态标题";
                }
                else
                {

                    var count = DynamicModelContract.Insert(entity);
                    var dynamicID = entity.Id;
                     
                    if (count > 0)
                    {


                        //添加楼盘动态ID
                        var Buildings = Request["BuildingsID"];
                        if (Buildings != null)
                        {
                            var BuildingsID = Buildings.Split(',');
                            DynamicPropertiesModel DynamicProperties = new DynamicPropertiesModel();
                            for (int i = 0; i < BuildingsID.Length; i++)
                            {
                                DynamicProperties.DynamicID = dynamicID;
                                DynamicProperties.BuildingsID = Convert.ToInt32(BuildingsID[i]);
                                DynamicPropertiesModelContract.Insert(DynamicProperties);
                            }
                        }
                         

                        //添加低价房动态ID
                        var LowPriceHouses = Request["LowPriceHousesID"];
                         

                        if (LowPriceHouses != null)
                        {
                            var LowPriceHousesID = LowPriceHouses.Split(',');
                            DynamicCheapRoomModel DynamicCheapRoom = new DynamicCheapRoomModel();
                            for (int o = 0; o < LowPriceHousesID.Length; o++)
                            {
                                DynamicCheapRoom.DynamicID = dynamicID;
                                DynamicCheapRoom.LowPriceHousesID = Convert.ToInt32(LowPriceHousesID[o]);
                                DynamicCheapRoomModelContract.Insert(DynamicCheapRoom);
                            }
                        }
                         

                        //添加装修动态ID
                        var Decoration = Request["DecorationID"];
                         

                        if (Decoration != null)
                        {
                            var DecorationID = Decoration.Split(',');
                            DynamicDecorationModel DynamicDecoratio = new DynamicDecorationModel();
                            for (int w = 0; w < DecorationID.Length; w++)
                            {
                                DynamicDecoratio.DynamicID = dynamicID;
                                DynamicDecoratio.DecorationID = Convert.ToInt32(DecorationID[w]);
                                DynamicDecorationModelContract.Insert(DynamicDecoratio);
                            }
                        }



                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    { 
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch (Exception ex)
            {
                //事务回滚
                DynamicPropertiesModelContract.Repository.UnitOfWork.Rollback();

                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            //结束事务
            DynamicDecorationModelContract.Repository.UnitOfWork.Commit();

            return JsonEx(result);
        }
        #endregion
        #region 动态修改
        [Description("动态管理-修改")]
        public ActionResult DynamicEdit(int id)
        {

            //innerce();
            //动态
            var entity = DynamicModelContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            //楼盘
            var DynamicPropertiesModel = DynamicPropertiesModelContract.TrackEntities.Where(m => m.DynamicID == id).ToList();
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (DynamicPropertiesModel == null) throw new Exception("未找到该实体");
            ViewData["DynamicPropertiesModel"] = DynamicPropertiesModel;
            //低价房
            var DynamicCheapRoomModel = DynamicCheapRoomModelContract.TrackEntities.Where(m => m.DynamicID == id).ToList();
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (DynamicCheapRoomModel == null) throw new Exception("未找到该实体");
            ViewData["DynamicCheapRoomModel"] = DynamicCheapRoomModel;
            //装修
            var DecorationModel = DynamicDecorationModelContract.TrackEntities.Where(m => m.DynamicID == id).ToList();
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (DecorationModel == null) throw new Exception("未找到该实体");
            ViewData["DecorationModel"] = DecorationModel;
            return View();
        }
        [HttpPost]
        public ActionResult EditDynamicAsync(DynamicModel entity)
        {
            entity.ReleaseTime = DateTime.Now;
            var result = new AjaxResult();
            try
            {  
                var query = DynamicModelContract.CheckExists(m => m.Title.Equals(entity.Title) && m.Id != entity.Id && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的动态标题";
                }
                else
                {
                    var dynamicID = entity.Id;


                    //开始事务
                    DynamicPropertiesModelContract.Repository.UnitOfWork.BeginTransaction(); 

                    //楼盘ID
                    var Propertiesid = DynamicPropertiesModelContract.TrackEntities.Where(p => p.DynamicID == dynamicID).ToList();
                    //删除楼盘ID原有记录
                    for (int i = 0; i < Propertiesid.Count; i++)
                    {
                        DynamicPropertiesModelContract.Delete(Propertiesid[i].Id);
                    }
                    var Buildings = Request["BuildingsID"]; 
                    if (Buildings != null)
                    {
                        //添加楼盘ID新记录
                        var BuildingsID = Buildings.Split(',');
                        DynamicPropertiesModel DynamicProperties = new DynamicPropertiesModel();
                        for (int i = 0; i < BuildingsID.Length; i++)
                        {
                            DynamicProperties.DynamicID = dynamicID;
                            DynamicProperties.BuildingsID = Convert.ToInt32(BuildingsID[i]);
                            DynamicPropertiesModelContract.Insert(DynamicProperties);
                        }
                    }
                     

                    //低价房ID
                    var CheapRoom = DynamicCheapRoomModelContract.TrackEntities.Where(c => c.DynamicID == dynamicID).ToList();
                       
                    //删除低价房ID原有记录
                    for (int i = 0; i < CheapRoom.Count; i++)
                    {
                        DynamicCheapRoomModelContract.Delete(CheapRoom[i].Id);
                    }
                    var LowPriceHouses = Request["LowPriceHousesID"];
                    if (LowPriceHouses != null)
                    {
                        //添加低价房ID新记录
                        var LowPriceHousesID = LowPriceHouses.Split(',');
                        DynamicCheapRoomModel DynamicCheapRoom = new DynamicCheapRoomModel();
                        for (int o = 0; o < LowPriceHousesID.Length; o++)
                        {
                            DynamicCheapRoom.DynamicID = dynamicID;
                            DynamicCheapRoom.LowPriceHousesID = Convert.ToInt32(LowPriceHousesID[o]);
                            DynamicCheapRoomModelContract.Insert(DynamicCheapRoom);
                        }
                    } 

                    //装修ID
                    var Decoration = DynamicDecorationModelContract.TrackEntities.Where(c => c.DynamicID == dynamicID).ToList();
                     
                    //删除装修ID原有记录
                    for (int i = 0; i < Decoration.Count; i++)
                    {
                        DynamicDecorationModelContract.Delete(Decoration[i].Id);
                    }
                    var DynamicDecoration = Request["DecorationID"];
                    if (DynamicDecoration != null)
                    {
                        //添加装修ID新记录
                        var DecorationID = DynamicDecoration.Split(',');
                        DynamicDecorationModel DynamicDecoratio = new DynamicDecorationModel();
                        for (int w = 0; w < DecorationID.Length; w++)
                        {
                            DynamicDecoratio.DynamicID = dynamicID;
                            DynamicDecoratio.DecorationID = Convert.ToInt32(DecorationID[w]);
                            DynamicDecorationModelContract.Insert(DynamicDecoratio);
                        }
                    } 


                    var count = DynamicModelContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {

                //事务回滚
                DynamicPropertiesModelContract.Repository.UnitOfWork.Rollback();

                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            //事务结束 
            DynamicPropertiesModelContract.Repository.UnitOfWork.Rollback();

            return JsonEx(result);
        }
        #endregion
        #region 动态删除
        [Description("动态管理-删除")]
        [HttpPost]
        public ActionResult DeleteDynamicAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                DynamicModelContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new DynamicModel { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
        #region 下拉列表
        //添加绑定
        public ActionResult GetBuildingsInsert()
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            var list = BuildingsContract.TrackEntities.Where(a => a.AgentID.Equals(agentid) && a.IsDeleted == false).ToList();//楼盘ID对应值   
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetLowPriceHousesInsert()
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            var list = LowPriceHouseBuildingsContract.TrackEntities.ToList();//楼盘ID对应值   
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetDecorationInsert()
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            var list = DecorationCompanyContract.TrackEntities.Where(a => a.AgentID.Equals(agentid) && a.IsDeleted == false).ToList();//楼盘ID对应值   
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        //修改绑定
        public ActionResult GetBuildings(int did)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            //var list = BuildingsContract.TrackEntities.Where(a => a.City.Equals(cid) && a.IsDeleted == false).ToList();//楼盘ID对应值  

            var list = from a in BuildingsContract.Entities
                       where a.AgentID == agentid
                       select new
                       {
                           ID = a.Id,
                           Name = a.Name,
                           Number = DynamicPropertiesModelContract.Entities.Count(p => p.BuildingsID == a.Id && p.DynamicID == did)
                       };

            return JsonEx(list.ToList(), JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetLowPriceHouses(int did)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            //var list = LowPriceHousesContract.TrackEntities.Where(a => a.CityID.Equals(cid) && a.IsDeleted == false).ToList();//低价房ID对应值  

            var list = from a in LowPriceHouseBuildingsContract.Entities 
                       select new
                       {
                           ID = a.Id,
                           Name = a.Name,
                           Number = DynamicCheapRoomModelContract.Entities.Count(p => p.LowPriceHousesID == a.Id && p.DynamicID == did)
                       };

            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetDecoration(int did)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            //var list = LowPriceHousesContract.TrackEntities.Where(a => a.CityID.Equals(cid) && a.IsDeleted == false).ToList();//低价房ID对应值  

            var list = from a in DecorationCompanyContract.Entities
                       where a.AgentID == agentid
                       select new
                       {
                           ID = a.Id,
                           Name = a.Name,
                           Number = DynamicDecorationModelContract.Entities.Count(p => p.DecorationID == a.Id && p.DynamicID == did)
                       };

            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}